import React from 'react';
import { Button, Col, Form, Input, message, Modal, Row } from 'antd';
import { connect, Dispatch } from 'umi';
import * as userApi from '@/services/information';
import DebounceSelect from '@/components/DebounceSelect';
import { createUser, isExistUser } from '@/services/information';
import './style.less';

interface AddModelProps {
  visible: boolean;
  onCancel: () => void;
  dispatch: Dispatch
}

const AddModel: React.FC<AddModelProps> = (props) => {
  const { visible, onCancel, dispatch } = props;
  const [data, setData] = React.useState([]);
  const [msg, setMsg] = React.useState<string>('');
  const [row, setRow] = React.useState<any>({});
  const [form] = Form.useForm();
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  const getSubStr = (str: string, position: number[] = [], end: number) => {
    let length = str.length;
    return (str.substring(position[0], position[1]) + '...' + str.substring(length - end, length));
  };

  const onFinish = (values: any) => {
    if (!values && !values.username) {
      return;
    }
    values = { ...values, email: row.email };
    isExistUser({ username: values.username }).then(resp => {
      const { payload } = resp;
      if (payload) {
        setMsg('该用户已添加');
      } else {
        createUser(values).then((rs: any) => {
          const { header } = rs;
          if (header.code === 200) {
            message.success('添加用户成功');
          } else {
            message.warning('添加失败');
          }
          dispatch({
            type: 'userManage/fetchUsers',
          });
          onCancel();
        });
      }
    });

  };
  const setPassport = (v:any={}) => {
    // form.resetFields()
    form.setFieldsValue({ 'username': v.username });
    form.setFieldsValue({ 'department': v.showDepartment });
    setRow(v);
  };
  const [value, setValue] = React.useState('');

  async function fetchUserList(username: string): Promise<any> {
    if (!username) {
      return;
    }
    return userApi.searchUser({ name: username, pageSize: 10 })
      .then(response => {
          const { header={}, payload } = response;
          if (header.code === 200) {
            if (payload && payload.length > 0) {
              let arr: any = [];
              payload.map((item: any) => {
                const { department } = item;
                item.showDepartment = getSubStr(department, [5, 12], 20).replaceAll('_', '/');
                arr.push({
                  label: item.name,
                  value: item.name,
                  ...item,
                });
              });
              setData(payload);
              return arr;
            }
          }
        },
      );
  }

  return (
    <Modal
      title="添加用户"
      visible={visible}
      onCancel={() => {
        onCancel();
      }}
      footer={
        null
      }
    >

      <div>
        <Col offset={4}>
          <span className={'tip'}>{msg}</span>
        </Col>
      </div>
      <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
        <Form.Item name="name" label="用户名：" rules={[{ required: true }]}>
          <DebounceSelect
            showSearch
            allowClear={true}
            showArrow={false}
            value={value}
            tooltip={{ title: 'department', show: 'showDepartment' }}
            placeholder="搜索用户名"
            fetchOptions={fetchUserList}
            onChange={newValue => {
              setMsg('');
              let current = data.filter((item: any) => item.name === newValue);
              setValue(newValue);
              setPassport(current[0]);
            }}
            style={{ width: '100%' }}
          />
        </Form.Item>
        <Form.Item name="username" label="通行证：">
          <Input disabled />
        </Form.Item>
        <Form.Item name="department" label="部门：">
          <Input disabled />
        </Form.Item>
        <Form.Item>
          <div className={'footer'}>
            <Col span={5}>
              <Button block onClick={_ => onCancel()}>
                取消
              </Button>
            </Col>
            <Col span={5}>
              <Button htmlType='submit'>
                添加用户
              </Button>
            </Col>
          </div>
        </Form.Item>
      </Form>
    </Modal>
  );

};

export default connect(({}: AddModelProps) => ({}))(AddModel);
